<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Form, Input, message, Radio } from 'ant-design-vue';

import { type DeptData, saveDeptApi } from '#/api/core/user';
import { $t } from '#/locales';

const emit = defineEmits<{
  save: [data: any];
}>();

interface FormState {
  id?: number | string;
  name: string;
  description: string;
  parentId: number | string;
  relationType: 'same' | 'sub';
}

const formRef = ref<FormInstance>();
const formState = ref<FormState>({
  name: '',
  description: '',
  parentId: '',
  relationType: 'sub',
});

async function onSubmit(values: FormState) {
  const deptData: DeptData = {
    name: values.name,
    description: values.description,
    pid: Number(values.parentId),
  };

  if (values.id) {
    deptData.id = Number(values.id);
  }

  await saveDeptApi(deptData);
}

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  async onConfirm() {
    try {
      await formRef.value?.validate();
      const { isEdit, parentId, id } = modalApi.getData<{
        id: number | string;
        isEdit: boolean;
        parentId: number | string;
      }>();

      const saveData = {
        ...formState.value,
        parentId: formState.value.relationType === 'same' ? parentId : id,
      };

      if (isEdit) {
        saveData.id = formState.value.id;
        saveData.parentId = formState.value.parentId;
      }

      await onSubmit(saveData);
      emit('save', saveData);
      modalApi.close();
      message.success($t('dept.save.success'));
      return true;
    } catch (error: any) {
      message.error(error.message || $t('dept.save.failed'));
      return false;
    }
  },
  onCancel() {
    formRef.value?.resetFields();
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        editData: any;
        isEdit: boolean;
        parentId: number | string;
      }>();

      formState.value = data.editData
        ? {
            id: data.editData.id,
            name: data.editData.name,
            description: data.editData.description,
            parentId: data.parentId,
            relationType: 'sub',
          }
        : {
            name: '',
            description: '',
            parentId: data.parentId,
            relationType: 'sub',
          };
    } else {
      formRef.value?.resetFields();
    }
  },
});

const showRelationType = computed(() => {
  const { isEdit, parentId } = modalApi.getData<{
    isEdit: boolean;
    parentId: number | string;
  }>();
  return !isEdit && Number(parentId) !== 0;
});
</script>

<template>
  <Modal>
    <Form
      ref="formRef"
      :label-col="{ span: 6 }"
      :model="formState"
      :wrapper-col="{ span: 18 }"
      layout="horizontal"
    >
      <Form.Item
        :label="$t('dept.form.name.label')"
        :rules="[{ required: true, message: $t('dept.form.name.required') }]"
        name="name"
      >
        <Input
          v-model:value="formState.name"
          :placeholder="$t('dept.form.name.placeholder')"
        />
      </Form.Item>

      <Form.Item :label="$t('dept.form.description.label')" name="description">
        <Input.TextArea
          v-model:value="formState.description"
          :placeholder="$t('dept.form.description.placeholder')"
          :rows="4"
        />
      </Form.Item>

      <Form.Item
        v-if="showRelationType"
        :label="$t('dept.form.relation.label')"
      >
        <Radio.Group v-model:value="formState.relationType">
          <Radio value="same">{{ $t('dept.form.relation.same') }}</Radio>
          <Radio value="sub">{{ $t('dept.form.relation.sub') }}</Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item name="parentId" style="display: none">
        <Input v-model:value="formState.parentId" />
      </Form.Item>
    </Form>
  </Modal>
</template>
